package com.skiving.cloud.admin.service.impl;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.skiving.cloud.admin.entity.SysOrg;
import com.skiving.cloud.admin.entity.SysStationMenu;
import com.skiving.cloud.admin.entity.SysUserStation;
import com.skiving.cloud.admin.mapper.SysOrgMapper;
import com.skiving.cloud.admin.mapper.SysStationMenuMapper;
import com.skiving.cloud.admin.mapper.SysUserStationMapper;
import com.skiving.cloud.auth.constant.AuthConstant;
import com.skiving.cloud.common.utils.PageParameter;
import com.skiving.cloud.admin.entity.SysStation;
import com.skiving.cloud.admin.mapper.SysStationMapper;
import com.skiving.cloud.admin.service.SysStationService;
import com.skiving.cloud.common.utils.UuidUtil;
import com.skiving.cloud.constant.AdminConstant;
import org.noear.solon.annotation.Component;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;

import java.util.Arrays;
import java.util.List;

/**
 * 岗位表 服务层实现。
 *
 * @author skivingcloud
 * @since 2025-03-08
 */
@Component
public class SysStationServiceImpl extends ServiceImpl<SysStationMapper, SysStation>  implements SysStationService {
    @Inject
    private SysStationMenuMapper sysStationMenuMapper;
    @Inject
    private SysUserStationMapper sysUserStationMapper;
    @Inject
    private SysOrgMapper sysOrgMapper;
    /**
     * 分页查询岗位表
     *
     * @param parameter 查询参数
     * @return 分页查询结果
     */
    @Override
    public Page<SysStation> queryByPage(PageParameter<SysStation> parameter){
        Page<SysStation> page = new Page<>(parameter.getPage(), parameter.getPageSize());
        QueryWrapper queryWrapper = QueryWrapper.create();
        if (parameter.getParam() != null) {
            //查询条件
            if (Utils.isNotBlank(parameter.getParam().getId())) {
                queryWrapper.and(SysStation::getId).like(parameter.getParam().getId());
            }
            if (Utils.isNotBlank(parameter.getParam().getStationCode())) {
                queryWrapper.and(SysStation::getStationCode).like(parameter.getParam().getStationCode());
            }
            if (Utils.isNotBlank(parameter.getParam().getStationName())) {
                queryWrapper.and(SysStation::getStationName).like(parameter.getParam().getStationName());
            }
            if (Utils.isNotBlank(parameter.getParam().getShortName())) {
                queryWrapper.and(SysStation::getShortName).like(parameter.getParam().getShortName());
            }
            if (Utils.isNotBlank(parameter.getParam().getOrgId())) {
                queryWrapper.and(SysStation::getOrgId).like(parameter.getParam().getOrgId());
            }
            if (Utils.isNotBlank(parameter.getParam().getStatus())) {
                queryWrapper.and(SysStation::getStatus).like(parameter.getParam().getStatus());
            }
            if (Utils.isNotBlank(parameter.getParam().getStationRank())) {
                queryWrapper.and(SysStation::getStationRank).like(parameter.getParam().getStationRank());
            }
            if (Utils.isNotBlank(parameter.getParam().getCreater())) {
                queryWrapper.and(SysStation::getCreater).like(parameter.getParam().getCreater());
            }
            if (Utils.isNotBlank(parameter.getParam().getModUser())) {
                queryWrapper.and(SysStation::getModUser).like(parameter.getParam().getModUser());
            }
            if (Utils.isNotBlank(parameter.getParam().getTenantId())) {
                queryWrapper.and(SysStation::getTenantId).like(parameter.getParam().getTenantId());
            }
        }
        return this.page(page, queryWrapper);
    }

    /**
     * 批量删除岗位信息
     *
     * @param ids 岗位ID
     */
    @Override
    @Transaction
    public void deleteBatch(String[] ids) {
        QueryWrapper sm = QueryWrapper.create();
        sm.where(SysStationMenu::getStationId).in(Arrays.stream(ids).toList());
        sysStationMenuMapper.deleteByQuery(sm);
        this.mapper.deleteBatchByIds(Arrays.stream(ids).toList());
    }

    /**
     * 仅设置岗位资源权限
     *
     * @param id    岗位ID
     * @param resId 资源ID
     */
    @Override
    @Transaction
    public void saveStationRes(String id, String[] resId) {
        QueryWrapper sm = QueryWrapper.create();
        sm.where(SysStationMenu::getStationId).eq(id);
        sysStationMenuMapper.deleteByQuery(sm);
        List<SysStationMenu> list = Arrays.stream(resId).map(r -> {
            SysStationMenu sysStationMenu = new SysStationMenu();
            sysStationMenu.setId(UuidUtil.get32UUID());
            sysStationMenu.setMenuId(r);
            sysStationMenu.setStationId(id);
            return sysStationMenu;
        }).toList();
        //批量插入
        Db.executeBatch(list, AdminConstant.BATCH_SIZE, SysStationMenuMapper.class, BaseMapper::insert);
    }

    /**
     * 根据租户获取岗位树
     *
     * @param tenantId 租户id
     * @return 岗位树
     */
    @Override
    public List<SysOrg> treeByTenantId(String tenantId) {
        QueryWrapper orgQueryWrapper = QueryWrapper.create().from(SysOrg.class).where(SysOrg::getTenantId).eq(tenantId)
                .and(SysOrg::getOrgStatus).eq(AuthConstant.COMMON_STATUS_NORMAL);
        List<SysOrg> orgList = sysOrgMapper.selectListByQuery(orgQueryWrapper);
        QueryWrapper stationQueryWrapper = QueryWrapper.create().from(SysStation.class).as("st")
                .join(SysOrg.class).as("o").on(wrapper -> wrapper.where(SysStation::getOrgId).eq(SysOrg::getId)
                ).where(SysOrg::getTenantId).eq(tenantId).and(SysOrg::getOrgStatus).eq(AuthConstant.COMMON_STATUS_NORMAL);
        List<SysStation> sysStations = this.list(stationQueryWrapper);
        orgList.addAll(sysStations.stream().map(m -> {
            SysOrg orgStation = new SysOrg();
            orgStation.setId(m.getId());
            orgStation.setOrgCode(m.getStationCode());
            orgStation.setOrgName(m.getStationName());
            orgStation.setParentId(m.getOrgId());
            orgStation.setDisabled(false);
            return orgStation;
        }).toList());
        return orgList.stream().filter(item -> {
            item.setChildren(orgList.stream().filter(e -> e.getParentId().equals(item.getId())).toList());
            return item.getParentId().equals("0");
        }).toList();
    }

    /**
     * 根据用户ID获取岗位集合
     *
     * @param userId 用户ID
     * @return 岗位信息
     */
    @Override
    public List<SysStation> getStationListByUserId(String userId) {
        QueryWrapper stationQueryWrapper = QueryWrapper.create().from(SysStation.class).as("st")
                .join(SysUserStation.class).as("su").on(
                        wrapper -> wrapper.where(SysStation::getId).eq(SysUserStation::getStationId))
                .where(SysUserStation::getUserId).eq(userId);
        return this.list(stationQueryWrapper);
    }
}
